package com.yami.shop.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.getui.push.v2.sdk.ApiHelper;
import com.getui.push.v2.sdk.api.PushApi;
import com.getui.push.v2.sdk.common.ApiResult;
import com.getui.push.v2.sdk.dto.CommonEnum;
import com.getui.push.v2.sdk.dto.req.Audience;
import com.getui.push.v2.sdk.dto.req.Settings;
import com.getui.push.v2.sdk.dto.req.Strategy;
import com.getui.push.v2.sdk.dto.req.message.PushChannel;
import com.getui.push.v2.sdk.dto.req.message.PushDTO;
import com.getui.push.v2.sdk.dto.req.message.PushMessage;
import com.getui.push.v2.sdk.dto.req.message.android.AndroidDTO;
import com.getui.push.v2.sdk.dto.req.message.android.GTNotification;
import com.getui.push.v2.sdk.dto.req.message.android.ThirdNotification;
import com.getui.push.v2.sdk.dto.req.message.android.Ups;
import com.getui.push.v2.sdk.dto.req.message.ios.Alert;
import com.getui.push.v2.sdk.dto.req.message.ios.Aps;
import com.getui.push.v2.sdk.dto.req.message.ios.IosDTO;
import com.yami.shop.bean.model.*;
import com.yami.shop.common.config.ApiContext;
import com.yami.shop.common.util.Arith;
import com.yami.shop.dao.UmsPayInformationMapper;
import com.yami.shop.service.*;
import org.apache.commons.collections.CollectionUtils;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional
public class UmsPayInformationServiceImpl extends ServiceImpl<UmsPayInformationMapper, UmsPayInformation> implements UmsPayInformationService {

    PushApi pushApi;

    ApiContext apiContext;

    @Autowired
    private UmsPayInformationMapper umsPayInformationMapper;

    @Autowired
    private OrderService orderService;
    @Autowired
    private SkuService skuService;
    @Autowired
    private OrderItemService orderItemService;
    @Autowired
    private ProductService productService;
    @Autowired
    private OrderSettlementService orderSettlementService;
    @Autowired
    private UserDepositService userDepositService;
    @Autowired
    private  UserService userService;

    @Override
    public void addNewUmsPayInformation(UmsPayInformation umsPayInformation) {
        umsPayInformationMapper.addNewUmsPayInformation(umsPayInformation);
    }

    @Override
    @Transactional
    public void dealPaySuccess(String  result,String orderNumber) {

        JSONObject jsonObj = new JSONObject(result);
        //errCode 当code为00的时候，表示支付成功
        String errCode =jsonObj.getString("errCode");
        if(errCode.equals("00")){
            //errInfo 错误说明
            String errInfo = jsonObj.getString("errInfo");
            //transactionTime 交易时间
            String transactionTime = jsonObj.getString("transactionTime");
            //transactionDate 交易日期
            String transactionDate = jsonObj.getString("transactionDate");
            //settlementDate 结算日期
            String settlementDate = jsonObj.getString("settlementDate");
            //交易日期 20210127
            String transactionDateWithYear = jsonObj.getString("transactionDateWithYear");
            //结算日期  20210127
            String settlementDateWithYear = jsonObj.getString("settlementDateWithYear");
            //检索参考号
            String retrievalRefNum = jsonObj.getString("retrievalRefNum");
            //交易金额
            Double transactionAmount = jsonObj.getDouble("transactionAmount");
            //营销联盟优惠后的交易价格
            Double actualTransactionAmount = jsonObj.getDouble("actualTransactionAmount");
            //实际支付金额
            Double amount = jsonObj.getDouble("amount");
            //银联订单号
            String orderId = jsonObj.getString("orderId");
            //第三方优惠说明
            String thirdPartyDiscountInstruction = jsonObj.getString("thirdPartyDiscountInstruction");
            //第三方名称
            String thirdPartyName = jsonObj.getString("thirdPartyName");
            //第三方用户ID thirdPartyBuyerId
            String thirdPartyBuyerId = jsonObj.getString("thirdPartyBuyerId");
            //第三方支付订单号
            String thirdPartyOrderId = jsonObj.getString("thirdPartyOrderId");
            //第三方支付信息
            String thirdPartyPayInformation = jsonObj.getString("thirdPartyPayInformation");

            UmsPayInformation umsPayInformation = new UmsPayInformation();
            umsPayInformation.setErrCode(errCode);
            umsPayInformation.setErrInfo(errInfo);
            umsPayInformation.setOrderNumber(orderNumber);
            umsPayInformation.setTransactionTime(transactionTime);
            umsPayInformation.setSettlementDate(settlementDate);
            umsPayInformation.setTransactionDateWithYear(transactionDateWithYear);
            umsPayInformation.setSettlementDateWithYear(settlementDateWithYear);
            umsPayInformation.setRetrievalRefNum(retrievalRefNum);
            umsPayInformation.setTransactionAmount(new BigDecimal(transactionAmount));
            umsPayInformation.setActualTransactionAmount(new BigDecimal(actualTransactionAmount));
            umsPayInformation.setAmount(new BigDecimal(amount));
            umsPayInformation.setOrderId(orderId);
            umsPayInformation.setThirdPartyDiscountInstruction(thirdPartyDiscountInstruction);
            umsPayInformation.setThirdPartyName(thirdPartyName);
            umsPayInformation.setThirdPartyBuyerId(thirdPartyBuyerId);
            umsPayInformation.setThirdPartyOrderId(thirdPartyOrderId);
            umsPayInformation.setThirdPartyPayInformation(thirdPartyPayInformation);
            umsPayInformation.setTransactionType(1);

            //向银联账户插入数据
            umsPayInformationMapper.addNewUmsPayInformation(umsPayInformation);
            //支付成功,修改订单状态
            Order order = orderService.getOrderByOrderNumber(orderNumber);
            order.setStatus(5);
            order.setPayType(2);
            BigDecimal unionPay = new BigDecimal(amount).divide(new BigDecimal("100")).setScale(2,BigDecimal.ROUND_HALF_UP);
            order.setUnionPay(unionPay);
            if(order.getMixedPayment()==1){
                //计算需要账户余额需要支付的金额
                BigDecimal oldAccount = order.getOldAccountPay();
                if(oldAccount.compareTo(new BigDecimal("0"))>-1){
                    Double remainAccount = Arith.sub(order.getActualTotal(),oldAccount.doubleValue());
                    order.setUnionPay(new BigDecimal(remainAccount));
                }
                BigDecimal userAccount = order.getNewAccountPay();
                if(userAccount.compareTo(new BigDecimal(0))>-1){
                    Double remainAccount = Arith.sub(order.getActualTotal(),userAccount.doubleValue());
                    order.setUnionPay(new BigDecimal(remainAccount));
                    order.setPayType(5);
                }

            }
            orderService.updateById(order);

            //添加销售数量
            List<OrderItem> orderItems = orderItemService.getOrderItemsByOrderNumber(orderNumber);
            if(CollectionUtils.isNotEmpty(orderItems)){
                for(OrderItem orderItem:orderItems){
                    Product product = productService.getProductByProdId(orderItem.getProdId());
                    product.setSoldNum(product.getSoldNum()+orderItem.getProdCount());
                    productService.saveOrUpdate(product);
                }
            }


            //向交易表中插入数据
            OrderSettlement orderSettlement = new OrderSettlement();
            orderSettlement.setPayNo(orderId);
            orderSettlement.setOrderNumber(orderNumber);
            orderSettlement.setPayType(1);
            //处理支付金额
            double actualMoney = Arith.div(amount,100);
            orderSettlement.setPayAmount(actualMoney);
            orderSettlement.setUserId(order.getUserId());
            orderSettlement.setCreateTime(new Date());
            orderSettlement.setVersion(1);
            orderSettlement.setPayStatus(1);
            orderSettlementService.save(orderSettlement);

            //商品库存数量减去已支付成功的商品数量
            List<OrderItem> orderItemList =orderItemService.getOrderItemsByOrderNumber(orderNumber);
            if(CollectionUtils.isNotEmpty(orderItemList)){
                for(OrderItem orderItem:orderItemList){
                    Long prodId = orderItem.getProdId();
                    int prodCount  = orderItem.getProdCount();
                    //查询对应的商品数量
                    Product product = productService.getProductByProdId(prodId);
                    int totalStocks = product.getTotalStocks();
                    int remainStock =  totalStocks - prodCount;
                    product.setTotalStocks(remainStock);
                    productService.saveOrUpdate(product);

                    //sku库存量修改
                    Long skuId = orderItem.getSkuId();
                    Sku sku = skuService.getSkuBySkuId(skuId);
                    int stocks =  sku.getStocks();
                    //剩余库存量
                    int leftStock =  stocks - prodCount;
                    sku.setStocks(leftStock);
                    skuService.saveOrUpdate(sku);
                }
            }
        }else if(errCode.equals("96")){
            System.out.println("交换中心异常");
        }


    }

    @Override
    public User dealPayByUms(String result,String orderNumber,Long depositId) {
        JSONObject jsonObj = new JSONObject(result);
        String errCode = jsonObj.getString("errCode");
        User user = null;
        if (errCode.equals("00")||errCode.equals("0000")) {
            String errInfo = jsonObj.getString("errInfo");
            //transactionTime 交易时间
            String transactionTime = jsonObj.getString("transactionTime");
            //transactionDate 交易日期
            String transactionDate = jsonObj.getString("transactionDate");
            //settlementDate 结算日期
            String settlementDate = jsonObj.getString("settlementDate");
            //交易日期 20210127
            String transactionDateWithYear = jsonObj.getString("transactionDateWithYear");
            //结算日期  20210127
            String settlementDateWithYear = jsonObj.getString("settlementDateWithYear");
            //检索参考号
            String retrievalRefNum = jsonObj.getString("retrievalRefNum");
            //交易金额
            Double transactionAmount = jsonObj.getDouble("transactionAmount");
            //营销联盟优惠后的交易价格
            Double actualTransactionAmount = jsonObj.getDouble("actualTransactionAmount");
            //实际支付金额
            Double amount = jsonObj.getDouble("amount");
            //银联订单号
            String orderId = jsonObj.getString("orderId");
            //第三方优惠说明
            String thirdPartyDiscountInstruction = jsonObj.getString("thirdPartyDiscountInstruction");
            //第三方名称
            String thirdPartyName = jsonObj.getString("thirdPartyName");
            //第三方用户ID thirdPartyBuyerId
            String thirdPartyBuyerId = jsonObj.getString("thirdPartyBuyerId");
            //第三方支付订单号
            String thirdPartyOrderId = jsonObj.getString("thirdPartyOrderId");
            //第三方支付信息
            String thirdPartyPayInformation = jsonObj.getString("thirdPartyPayInformation");

            UmsPayInformation umsPayInformation = new UmsPayInformation();
            umsPayInformation.setErrCode(errCode);
            umsPayInformation.setErrInfo(errInfo);
            umsPayInformation.setOrderNumber(orderNumber);
            umsPayInformation.setTransactionTime(transactionTime);
            umsPayInformation.setSettlementDate(settlementDate);
            umsPayInformation.setTransactionDateWithYear(transactionDateWithYear);
            umsPayInformation.setSettlementDateWithYear(settlementDateWithYear);
            umsPayInformation.setRetrievalRefNum(retrievalRefNum);
            umsPayInformation.setTransactionAmount(new BigDecimal(transactionAmount));
            umsPayInformation.setActualTransactionAmount(new BigDecimal(actualTransactionAmount));
            umsPayInformation.setAmount(new BigDecimal(amount));
            umsPayInformation.setOrderId(orderId);
            umsPayInformation.setThirdPartyDiscountInstruction(thirdPartyDiscountInstruction);
            umsPayInformation.setThirdPartyName(thirdPartyName);
            umsPayInformation.setThirdPartyBuyerId(thirdPartyBuyerId);
            umsPayInformation.setThirdPartyOrderId(thirdPartyOrderId);
            umsPayInformation.setThirdPartyPayInformation(thirdPartyPayInformation);
            umsPayInformation.setTransactionType(2);

            //向银联账户插入数据
            umsPayInformationMapper.addNewUmsPayInformation(umsPayInformation);

            //修改充值记录表数据
            UserDeposit userDeposit = userDepositService.getDepositRecordByDepositId(depositId);
            Double payAmount = 0.00;
            if (userDeposit != null) {
                payAmount = userDeposit.getAmount();
                userDeposit.setPayType(2);
                userDeposit.setStatus(1);
                userDeposit.setUpdateTime(new Date());
                userDepositService.saveOrUpdate(userDeposit);
            }

            //向用户账户充值金额
            String userId = userDeposit.getUserId();
             user = userService.getUserByUserId(userId);
            //查询当前账户有没有余额 对当前余额进行累加
            Double userAccount = user.getUserAccount();
            if (userAccount == null) {
                userAccount = 0.00;
            }
            Double currentAmount = Arith.add(payAmount, userAccount);
            user.setUserAccount(currentAmount);
            user.setVipLevel(1);
            userService.updateById(user);
            System.out.println("充值成功返回数据 "+user);
        }
        return user;
    }
}
